﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace PicStore.Web
{
    public interface IContainerAccessor
    {
        IUnityContainer Container { get; }
    }

    public class UnityControllerFactory : IControllerFactory
    {
        #region IControllerFactory Members

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            IContainerAccessor containerAccessor =
                requestContext.HttpContext.ApplicationInstance as IContainerAccessor;

            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            string name = (controllerName + "Controller").ToLower();
            var controllerTypes = from t in currentAssembly.GetTypes()
                                  where t.Name.ToLower().Contains(name)
                                  select t;

            if (controllerTypes.Count() > 0)
            {
                return containerAccessor.Container.Resolve(controllerTypes.First()) as IController;
            }
            return null;
        }

        public void ReleaseController(IController controller)
        {
            controller = null;
        }

        public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return System.Web.SessionState.SessionStateBehavior.Default;
        }

        #endregion
    }
}